package com.jsjosem.aftersales.ui.notifications;

import static com.jsjosem.aftersales.constant.Command.NOTIFY_REFRESH_EVENT_INFO_DATA;
import static com.jsjosem.aftersales.utils.CommonUtils.getInstalledAppList;
import static com.jsjosem.aftersales.utils.CommonUtils.startNavi;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.jsjosem.aftersales.R;
import com.jsjosem.aftersales.adapter.StateAdapter;
import com.jsjosem.aftersales.api.EventApi;
import com.jsjosem.aftersales.api.RetrofitClient;
import com.jsjosem.aftersales.component.DrawableHorizontalButton;
import com.jsjosem.aftersales.component.NodeProcessBar;
import com.jsjosem.aftersales.data.model.AppInfo;
import com.jsjosem.aftersales.data.response.BaseResponse;
import com.jsjosem.aftersales.data.response.CustomerResponse;
import com.jsjosem.aftersales.data.response.EventResponse;
import com.jsjosem.aftersales.data.response.LogResponse;
import com.jsjosem.aftersales.listener.IListener;
import com.jsjosem.aftersales.listener.ListenerManager;
import com.jsjosem.aftersales.request.AsyncRequest;
import com.jsjosem.aftersales.utils.ViewUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Objects;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import retrofit2.Call;
import retrofit2.Retrofit;

public class ServiceEventInfoActivity extends AppCompatActivity implements IListener {

    private DrawableHorizontalButton btCallPhone, btLocation;
    private NodeProcessBar nodeProcessBar;
    private TextView tvContact, tvEventStatus, tvCustomerName, tvAddressValue, tvPhone, tvMsg, tvProcessCreateTime;
    private String phone;
    private final List<String> mapAppPkgName = ListUtil.of("com.baidu.BaiduMap", "com.tencent.map", "com.autonavi.minimap");
    private ViewPager2 viewPager2;
    private TabLayout tabLayout;
    private EventResponse eventResponse;
    private Retrofit mRetrofit;
    private StateAdapter stateAdapter;
    private String eventId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_event_info);
        // 初始化view，获取view
        initView();
        // 初始化view的数据
        initData();
        // 打电话
        callPhone();
        // 导航底部弹窗
        naviBottomDialog();
        // 事件信息和回单信息

        // 注册监听回调事件
        ListenerManager.getInstance().registerListener(this);
    }

    private void initData() {
        // 从intent过来拿数据的方式
        Intent intent = getIntent();
        eventId = intent.getStringExtra("eventId");
        loadEventInfo();
    }

    private void loadEventInfo() {
        EventApi eventApi = mRetrofit.create(EventApi.class);
        Call<BaseResponse<EventResponse>> eventInfoCall = eventApi.getEventInfoById(Integer.valueOf(eventId));
        AsyncRequest<BaseResponse<EventResponse>> eventInfoReq = new AsyncRequest<>();
        eventInfoReq.sendRequest(eventInfoCall, (eventInfoRes) -> {
            eventResponse = eventInfoRes.getData();
            // 设置进度条
            String status = eventResponse.getStatus();
            HashSet<Integer> selected = new HashSet<>();
            // 默认选中第一个
            selected.add(0);
            List<String> statusList = ListUtil.of("待分配", "已分配", "已完成");
            for (int i = 0; i < statusList.size(); i++) {
                selected.add(i);
                if (StrUtil.equals(statusList.get(i), status)) {
                    break;
                }
            }
            nodeProcessBar.show(statusList, selected);
            tvEventStatus.setText(status);
            CustomerResponse customer = eventResponse.getCustomer();
            if (Objects.nonNull(customer)) {
                tvCustomerName.setText(customer.getName());
            }
            tvAddressValue.setText(eventResponse.getAddress());
            phone = eventResponse.getContact_telephone();
            tvPhone.setText(phone);
            tvContact.setText(eventResponse.getContact_name());
            List<LogResponse> logs = eventResponse.getLogs();
            if (CollUtil.isNotEmpty(logs)) {
                LogResponse log = logs.get(logs.size() - 1);
                String format = String.format("%s %s", log.getCreator(), log.getAction());
                tvMsg.setText(format);
                tvProcessCreateTime.setText(log.getCreateTime());
            }
            initViewPage();
        }, failedMessage -> Toast.makeText(this, failedMessage.toString(), Toast.LENGTH_SHORT).show());
    }

    private void initView() {
        nodeProcessBar = findViewById(R.id.nodeProcessBar);
        tvEventStatus = findViewById(R.id.tv_event_status);
        tvCustomerName = findViewById(R.id.customerName);
        tvAddressValue = findViewById(R.id.addressValue);
        btCallPhone = findViewById(R.id.callPhoneBt);
        btLocation = findViewById(R.id.locationBt);
        tvContact = findViewById(R.id.contactValue);
        tvPhone = findViewById(R.id.tv_phone);
        tvMsg = findViewById(R.id.msgTv);
        tvProcessCreateTime = findViewById(R.id.processCreateTimeTv);
        viewPager2 = findViewById(R.id.eventInfoViewPage);
        tabLayout = findViewById(R.id.eventInfoTabLayout);
        mRetrofit = RetrofitClient.getInstance();
        stateAdapter = new StateAdapter(this);
    }

    private void initViewPage() {
        stateAdapter.clearAllFragment();
        stateAdapter.addFragment(EventInfoFragment.newInstance(eventResponse));
        String type_text = eventResponse.getStatus();
        // 只有已完成才有回单信息
        if (StrUtil.equals(type_text, "已完成")) {
            stateAdapter.addFragment(EventReceiptInfoFragment.newInstance(eventResponse.getReceipt()));
        }
        viewPager2.setOffscreenPageLimit(stateAdapter.getItemCount());
        viewPager2.setAdapter(stateAdapter);
        viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                View view = stateAdapter.getFragment(position).getView();
                if (Objects.isNull(view)) {
                    return;
                }
                ViewUtils.updatePagerHeightForChild(view, viewPager2);
            }
        });

        List<String> stateList = ListUtil.of("事件信息", "回单信息");
        new TabLayoutMediator(tabLayout, viewPager2, (tab, position) -> {
            String state = stateList.get(position);
            tab.setText(state);
        }).attach();
    }

    private void naviBottomDialog() {
        btLocation.setOnClickListener(view -> {
            List<AppInfo> appList = getInstalledAppList(this, mapAppPkgName);
            if (CollUtil.isEmpty(appList)) {
                Toast.makeText(this, "未安装常用地图软件,无法导航,目前支持: 高德地图导航,百度地图导航,腾讯地图导航", Toast.LENGTH_LONG).show();
                return;
            }
            String targetAddress = tvAddressValue.getText().toString();
            startNavi(this, appList, targetAddress);
        });
    }

    private void callPhone() {
        btCallPhone.setOnClickListener(view -> {
            if (StrUtil.isBlank(phone)) {
                Toast.makeText(this, "没有电话号码", Toast.LENGTH_SHORT).show();
                return;
            }
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        });
    }

    @Override
    public void notifyAllActivity(int flag, String data, String message) {
        this.runOnUiThread(() -> {
            // 刷新页面数据
            if (flag == NOTIFY_REFRESH_EVENT_INFO_DATA) {
                // 分配成功，获取事件详情，刷新详情页数据
                loadEventInfo();
            }
        });
    }
}